<template lang="pug">
div
  //- Button(@click='add') add
  div(style='margin-bottom: 20px')
    router-link(to='articles/add') 添加文章
  Table(:columns='cols', :data='articles')
</template>

<script>
import Api from '@/apis/article'
export default {
  beforeRouteEnter (to, from, next) {
    Api.getArticles(2).then(data => {
      console.log(data)
      next(vm => {
        vm.articles = data
      })
    })
  },
  data () {
    return {
      cols: [
        { title: '标题', key: 'title' },
        { title: '更新时间', key: 'changed' },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.$router.push(`/articles/${params.row.id}/edit`)
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.remove(params.index)
                  }
                }
              }, '删除')
            ])
          }
        }
      ],
      articles: []
    }
  },
  methods: {
    add () {
      // alert('add')
      Api.postArticle({
        title: 'test article',
        body: 'test article from app post.',
        group_id: 2
      })
    },
    remove (idx) {
      this.$Modal.confirm({
        title: '删除确认',
        content: `删除 < ${this.articles[idx].title} > 吗？`,
        loading: true,
        onOk: () => {
          const id = this.articles[idx].id
          Api.deleteArticle(id).then(() => {
            this.$Message.success('删除成功')
            this.articles.splice(idx, 1)
            this.$Modal.remove()
          })
        }
      })
    }
  }
}
</script>
